{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 注意力机制\n",
    "\n",
    "## 生物中的注意力提示\n",
    "\n",
    "* 使用基于突出性的非自主性提示（红茶杯，而非纸张）。注意力不自主地指向了咖啡\n",
    "* 通过使用依赖于任务的意志提示，注意力被自主引导到纸上\n",
    "\n",
    "## 查询、键和值\n",
    "\n",
    "首先，考虑一个简单情况，对于非自主性提示，要想将选择偏向于感官输入，我们可以简单地使用参数化的全连接层，甚至是非参数化的最大汇聚层或平均汇聚层。\n",
    "\n",
    "因此，通过是否包含自主性提示将注意力机制与全连接层或汇聚层区别开来。\n",
    "\n",
    "* 在注意力背景下，我们将**自主性提示**成为查询（Queries）\n",
    "  * 给定任何查询，注意力机制通过注意力汇聚（attention pooling）将选择偏向于感官输入（sensory inputs，例如中间特征表示）\n",
    "* 在注意力背景下，这些感官输入被成为值（Values)\n",
    "* 这些值都与一个键（Keys）配对，这可以想象为感官输入的非自主提示。\n",
    "\n",
    "![img](../img/attention_key_values.svg)  \n",
    "注意力机制通过注意力汇聚将查询（自主性提示）和键（非自主性提示）结合在一起，实现对值（感官输入）的选择倾向\n",
    "\n",
    "## 注意力的可视化\n",
    "\n",
    "平均汇聚层可以被视为输入的加权平均值，其中各输入的权重是一样的。实际上，注意力汇聚得到的是加权平均的总和值，其中权重是在给定的查询和不同的键之间计算得到的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import d2lzh_pytorch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show_heatmaps(matrices,xlabel,ylabel,titles=None,figsize=(2.5,2.5),cmap='Reds'):\n",
    "    d2l.use_svg_display()\n",
    "    num_rows,num_cols=matrices.shape[0],matrices.shape[1]\n",
    "\n",
    "    # sharex, sharey : `~.axes.Axes`, optional\n",
    "    # Share the x or y `~matplotlib.axis` with sharex and/or sharey. \n",
    "    # The axis will have the same limits, ticks, and scale as the axis of the shared axes.\n",
    "    fig, axes=d2l.plt.subplots(num_rows,num_cols,figsize=figsize,sharex=True,sharey=True,squeeze=False)\n",
    "    for i, (row_axes,row_matrices) in enumerate(zip(axes,matrices)):\n",
    "        for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)):\n",
    "            pcm = ax.imshow(matrix.detach().numpy(), cmap=cmap)\n",
    "            if i == num_rows - 1:\n",
    "                ax.set_xlabel(xlabel)\n",
    "            if j == 0:\n",
    "                ax.set_ylabel(ylabel)\n",
    "            if titles:\n",
    "                ax.set_title(titles[j])\n",
    "    fig.colorbar(pcm, ax=axes, shrink=0.6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on class zip in module builtins:\n",
      "\n",
      "class zip(object)\n",
      " |  zip(*iterables) --> A zip object yielding tuples until an input is exhausted.\n",
      " |  \n",
      " |     >>> list(zip('abcdefg', range(3), range(4)))\n",
      " |     [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]\n",
      " |  \n",
      " |  The zip object yields n-length tuples, where n is the number of iterables\n",
      " |  passed as positional arguments to zip().  The i-th element in every tuple\n",
      " |  comes from the i-th iterable argument to zip().  This continues until the\n",
      " |  shortest argument is exhausted.\n",
      " |  \n",
      " |  Methods defined here:\n",
      " |  \n",
      " |  __getattribute__(self, name, /)\n",
      " |      Return getattr(self, name).\n",
      " |  \n",
      " |  __iter__(self, /)\n",
      " |      Implement iter(self).\n",
      " |  \n",
      " |  __next__(self, /)\n",
      " |      Implement next(self).\n",
      " |  \n",
      " |  __reduce__(...)\n",
      " |      Return state information for pickling.\n",
      " |  \n",
      " |  ----------------------------------------------------------------------\n",
      " |  Static methods defined here:\n",
      " |  \n",
      " |  __new__(*args, **kwargs) from builtins.type\n",
      " |      Create and return a new object.  See help(type) for accurate signature.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(zip)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
       "          [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
       "          [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],\n",
       "          [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],\n",
       "          [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],\n",
       "          [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n",
       "          [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],\n",
       "          [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],\n",
       "          [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],\n",
       "          [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.eye(10).reshape(1,1,10,10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[<AxesSubplot:>]\n",
      "tensor([[[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]])\n",
      "tensor([[[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],\n",
      "         [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]])\n",
      "tensor([[[[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "          [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],\n",
      "          [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],\n",
      "          [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],\n",
      "          [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],\n",
      "          [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n",
      "          [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],\n",
      "          [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],\n",
      "          [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],\n",
      "          [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]]])\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\r\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\r\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\r\n<!-- Created with matplotlib (https://matplotlib.org/) -->\r\n<svg height=\"156.35625pt\" version=\"1.1\" viewBox=\"0 0 193.35825 156.35625\" width=\"193.35825pt\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\r\n <metadata>\r\n  <rdf:RDF xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\r\n   <cc:Work>\r\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\r\n    <dc:date>2021-11-25T15:04:29.621638</dc:date>\r\n    <dc:format>image/svg+xml</dc:format>\r\n    <dc:creator>\r\n     <cc:Agent>\r\n      <dc:title>Matplotlib v3.3.4, https://matplotlib.org/</dc:title>\r\n     </cc:Agent>\r\n    </dc:creator>\r\n   </cc:Work>\r\n  </rdf:RDF>\r\n </metadata>\r\n <defs>\r\n  <style type=\"text/css\">*{stroke-linecap:butt;stroke-linejoin:round;}</style>\r\n </defs>\r\n <g id=\"figure_1\">\r\n  <g id=\"patch_1\">\r\n   <path d=\"M -0 156.35625 \r\nL 193.35825 156.35625 \r\nL 193.35825 0 \r\nL -0 0 \r\nz\r\n\" style=\"fill:none;\"/>\r\n  </g>\r\n  <g id=\"axes_1\">\r\n   <g id=\"patch_2\">\r\n    <path d=\"M 34.240625 118.8 \r\nL 145.840625 118.8 \r\nL 145.840625 7.2 \r\nL 34.240625 7.2 \r\nz\r\n\" style=\"fill:#ffffff;\"/>\r\n   </g>\r\n   <g clip-path=\"url(#p57057f4988)\">\r\n    <image height=\"112\" id=\"image9a10459acb\" transform=\"scale(1 -1)translate(0 -112)\" width=\"112\" x=\"34.240625\" xlink:href=\"data:image/png;base64,\r\niVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAYAAADG4PRLAAABc0lEQVR4nO3dsW3CUBhGURPRJSNkPxgpA2YAGmqnpfRDMnnXnFO7sHT1N58s+bTeb+vCVK6f35uf/djxPXgBAeMEjBMwTsA4AeMEjBMwTsA4AePO//0C72JkHvu5/25+1gXGCRgnYJyAcQLGCRgnYJyAcQLGCRhnSnvSyDS2LGPz2AgXGCdgnIBxAsYJGCdgnIBxAsYJGCdgnIBxttAHe336tycXGCdgnIBxAsYJGCdgnIBxAsYJGCdg3OGntOI8NsIFxgkYJ2CcgHECxgkYJ2CcgHECxgkYl5zSjj6PjXCBcQLGCRgnYJyAcQLGCRgnYJyAcQLGTTOlmcee4wLjBIwTME7AOAHjBIwTME7AOAHjBIzbbUqb5b8KR+cC4wSMEzBOwDgB4wSMEzBOwDgB4wSMEzBuaAv16d98XGCcgHECxgkYJ2CcgHECxgkYJ2CcgHGny/K1bn3YPDYfFxgnYJyAcQLGCRgnYJyAcQLGCRgnYNwfkEghRAiKZdAAAAAASUVORK5CYII=\" y=\"-6.8\"/>\r\n   </g>\r\n   <g id=\"matplotlib.axis_1\">\r\n    <g id=\"xtick_1\">\r\n     <g id=\"line2d_1\">\r\n      <defs>\r\n       <path d=\"M 0 0 \r\nL 0 3.5 \r\n\" id=\"mfdbd0b2c75\" style=\"stroke:#000000;stroke-width:0.8;\"/>\r\n      </defs>\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"39.820625\" xlink:href=\"#mfdbd0b2c75\" y=\"118.8\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_1\">\r\n      <!-- 0 -->\r\n      <g transform=\"translate(36.639375 133.398438)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 31.78125 66.40625 \r\nQ 24.171875 66.40625 20.328125 58.90625 \r\nQ 16.5 51.421875 16.5 36.375 \r\nQ 16.5 21.390625 20.328125 13.890625 \r\nQ 24.171875 6.390625 31.78125 6.390625 \r\nQ 39.453125 6.390625 43.28125 13.890625 \r\nQ 47.125 21.390625 47.125 36.375 \r\nQ 47.125 51.421875 43.28125 58.90625 \r\nQ 39.453125 66.40625 31.78125 66.40625 \r\nz\r\nM 31.78125 74.21875 \r\nQ 44.046875 74.21875 50.515625 64.515625 \r\nQ 56.984375 54.828125 56.984375 36.375 \r\nQ 56.984375 17.96875 50.515625 8.265625 \r\nQ 44.046875 -1.421875 31.78125 -1.421875 \r\nQ 19.53125 -1.421875 13.0625 8.265625 \r\nQ 6.59375 17.96875 6.59375 36.375 \r\nQ 6.59375 54.828125 13.0625 64.515625 \r\nQ 19.53125 74.21875 31.78125 74.21875 \r\nz\r\n\" id=\"DejaVuSans-48\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-48\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"xtick_2\">\r\n     <g id=\"line2d_2\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"95.620625\" xlink:href=\"#mfdbd0b2c75\" y=\"118.8\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_2\">\r\n      <!-- 5 -->\r\n      <g transform=\"translate(92.439375 133.398438)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 10.796875 72.90625 \r\nL 49.515625 72.90625 \r\nL 49.515625 64.59375 \r\nL 19.828125 64.59375 \r\nL 19.828125 46.734375 \r\nQ 21.96875 47.46875 24.109375 47.828125 \r\nQ 26.265625 48.1875 28.421875 48.1875 \r\nQ 40.625 48.1875 47.75 41.5 \r\nQ 54.890625 34.8125 54.890625 23.390625 \r\nQ 54.890625 11.625 47.5625 5.09375 \r\nQ 40.234375 -1.421875 26.90625 -1.421875 \r\nQ 22.3125 -1.421875 17.546875 -0.640625 \r\nQ 12.796875 0.140625 7.71875 1.703125 \r\nL 7.71875 11.625 \r\nQ 12.109375 9.234375 16.796875 8.0625 \r\nQ 21.484375 6.890625 26.703125 6.890625 \r\nQ 35.15625 6.890625 40.078125 11.328125 \r\nQ 45.015625 15.765625 45.015625 23.390625 \r\nQ 45.015625 31 40.078125 35.4375 \r\nQ 35.15625 39.890625 26.703125 39.890625 \r\nQ 22.75 39.890625 18.8125 39.015625 \r\nQ 14.890625 38.140625 10.796875 36.28125 \r\nz\r\n\" id=\"DejaVuSans-53\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-53\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"text_3\">\r\n     <!-- Keys -->\r\n     <g transform=\"translate(78.371094 147.076563)scale(0.1 -0.1)\">\r\n      <defs>\r\n       <path d=\"M 9.8125 72.90625 \r\nL 19.671875 72.90625 \r\nL 19.671875 42.09375 \r\nL 52.390625 72.90625 \r\nL 65.09375 72.90625 \r\nL 28.90625 38.921875 \r\nL 67.671875 0 \r\nL 54.6875 0 \r\nL 19.671875 35.109375 \r\nL 19.671875 0 \r\nL 9.8125 0 \r\nz\r\n\" id=\"DejaVuSans-75\"/>\r\n       <path d=\"M 56.203125 29.59375 \r\nL 56.203125 25.203125 \r\nL 14.890625 25.203125 \r\nQ 15.484375 15.921875 20.484375 11.0625 \r\nQ 25.484375 6.203125 34.421875 6.203125 \r\nQ 39.59375 6.203125 44.453125 7.46875 \r\nQ 49.3125 8.734375 54.109375 11.28125 \r\nL 54.109375 2.78125 \r\nQ 49.265625 0.734375 44.1875 -0.34375 \r\nQ 39.109375 -1.421875 33.890625 -1.421875 \r\nQ 20.796875 -1.421875 13.15625 6.1875 \r\nQ 5.515625 13.8125 5.515625 26.8125 \r\nQ 5.515625 40.234375 12.765625 48.109375 \r\nQ 20.015625 56 32.328125 56 \r\nQ 43.359375 56 49.78125 48.890625 \r\nQ 56.203125 41.796875 56.203125 29.59375 \r\nz\r\nM 47.21875 32.234375 \r\nQ 47.125 39.59375 43.09375 43.984375 \r\nQ 39.0625 48.390625 32.421875 48.390625 \r\nQ 24.90625 48.390625 20.390625 44.140625 \r\nQ 15.875 39.890625 15.1875 32.171875 \r\nz\r\n\" id=\"DejaVuSans-101\"/>\r\n       <path d=\"M 32.171875 -5.078125 \r\nQ 28.375 -14.84375 24.75 -17.8125 \r\nQ 21.140625 -20.796875 15.09375 -20.796875 \r\nL 7.90625 -20.796875 \r\nL 7.90625 -13.28125 \r\nL 13.1875 -13.28125 \r\nQ 16.890625 -13.28125 18.9375 -11.515625 \r\nQ 21 -9.765625 23.484375 -3.21875 \r\nL 25.09375 0.875 \r\nL 2.984375 54.6875 \r\nL 12.5 54.6875 \r\nL 29.59375 11.921875 \r\nL 46.6875 54.6875 \r\nL 56.203125 54.6875 \r\nz\r\n\" id=\"DejaVuSans-121\"/>\r\n       <path d=\"M 44.28125 53.078125 \r\nL 44.28125 44.578125 \r\nQ 40.484375 46.53125 36.375 47.5 \r\nQ 32.28125 48.484375 27.875 48.484375 \r\nQ 21.1875 48.484375 17.84375 46.4375 \r\nQ 14.5 44.390625 14.5 40.28125 \r\nQ 14.5 37.15625 16.890625 35.375 \r\nQ 19.28125 33.59375 26.515625 31.984375 \r\nL 29.59375 31.296875 \r\nQ 39.15625 29.25 43.1875 25.515625 \r\nQ 47.21875 21.78125 47.21875 15.09375 \r\nQ 47.21875 7.46875 41.1875 3.015625 \r\nQ 35.15625 -1.421875 24.609375 -1.421875 \r\nQ 20.21875 -1.421875 15.453125 -0.5625 \r\nQ 10.6875 0.296875 5.421875 2 \r\nL 5.421875 11.28125 \r\nQ 10.40625 8.6875 15.234375 7.390625 \r\nQ 20.0625 6.109375 24.8125 6.109375 \r\nQ 31.15625 6.109375 34.5625 8.28125 \r\nQ 37.984375 10.453125 37.984375 14.40625 \r\nQ 37.984375 18.0625 35.515625 20.015625 \r\nQ 33.0625 21.96875 24.703125 23.78125 \r\nL 21.578125 24.515625 \r\nQ 13.234375 26.265625 9.515625 29.90625 \r\nQ 5.8125 33.546875 5.8125 39.890625 \r\nQ 5.8125 47.609375 11.28125 51.796875 \r\nQ 16.75 56 26.8125 56 \r\nQ 31.78125 56 36.171875 55.265625 \r\nQ 40.578125 54.546875 44.28125 53.078125 \r\nz\r\n\" id=\"DejaVuSans-115\"/>\r\n      </defs>\r\n      <use xlink:href=\"#DejaVuSans-75\"/>\r\n      <use x=\"60.576172\" xlink:href=\"#DejaVuSans-101\"/>\r\n      <use x=\"122.099609\" xlink:href=\"#DejaVuSans-121\"/>\r\n      <use x=\"181.279297\" xlink:href=\"#DejaVuSans-115\"/>\r\n     </g>\r\n    </g>\r\n   </g>\r\n   <g id=\"matplotlib.axis_2\">\r\n    <g id=\"ytick_1\">\r\n     <g id=\"line2d_3\">\r\n      <defs>\r\n       <path d=\"M 0 0 \r\nL -3.5 0 \r\n\" id=\"mfd42408965\" style=\"stroke:#000000;stroke-width:0.8;\"/>\r\n      </defs>\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"34.240625\" xlink:href=\"#mfd42408965\" y=\"12.78\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_4\">\r\n      <!-- 0 -->\r\n      <g transform=\"translate(20.878125 16.579219)scale(0.1 -0.1)\">\r\n       <use xlink:href=\"#DejaVuSans-48\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_2\">\r\n     <g id=\"line2d_4\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"34.240625\" xlink:href=\"#mfd42408965\" y=\"35.1\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_5\">\r\n      <!-- 2 -->\r\n      <g transform=\"translate(20.878125 38.899219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 19.1875 8.296875 \r\nL 53.609375 8.296875 \r\nL 53.609375 0 \r\nL 7.328125 0 \r\nL 7.328125 8.296875 \r\nQ 12.9375 14.109375 22.625 23.890625 \r\nQ 32.328125 33.6875 34.8125 36.53125 \r\nQ 39.546875 41.84375 41.421875 45.53125 \r\nQ 43.3125 49.21875 43.3125 52.78125 \r\nQ 43.3125 58.59375 39.234375 62.25 \r\nQ 35.15625 65.921875 28.609375 65.921875 \r\nQ 23.96875 65.921875 18.8125 64.3125 \r\nQ 13.671875 62.703125 7.8125 59.421875 \r\nL 7.8125 69.390625 \r\nQ 13.765625 71.78125 18.9375 73 \r\nQ 24.125 74.21875 28.421875 74.21875 \r\nQ 39.75 74.21875 46.484375 68.546875 \r\nQ 53.21875 62.890625 53.21875 53.421875 \r\nQ 53.21875 48.921875 51.53125 44.890625 \r\nQ 49.859375 40.875 45.40625 35.40625 \r\nQ 44.1875 33.984375 37.640625 27.21875 \r\nQ 31.109375 20.453125 19.1875 8.296875 \r\nz\r\n\" id=\"DejaVuSans-50\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-50\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_3\">\r\n     <g id=\"line2d_5\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"34.240625\" xlink:href=\"#mfd42408965\" y=\"57.42\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_6\">\r\n      <!-- 4 -->\r\n      <g transform=\"translate(20.878125 61.219219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 37.796875 64.3125 \r\nL 12.890625 25.390625 \r\nL 37.796875 25.390625 \r\nz\r\nM 35.203125 72.90625 \r\nL 47.609375 72.90625 \r\nL 47.609375 25.390625 \r\nL 58.015625 25.390625 \r\nL 58.015625 17.1875 \r\nL 47.609375 17.1875 \r\nL 47.609375 0 \r\nL 37.796875 0 \r\nL 37.796875 17.1875 \r\nL 4.890625 17.1875 \r\nL 4.890625 26.703125 \r\nz\r\n\" id=\"DejaVuSans-52\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-52\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_4\">\r\n     <g id=\"line2d_6\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"34.240625\" xlink:href=\"#mfd42408965\" y=\"79.74\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_7\">\r\n      <!-- 6 -->\r\n      <g transform=\"translate(20.878125 83.539219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 33.015625 40.375 \r\nQ 26.375 40.375 22.484375 35.828125 \r\nQ 18.609375 31.296875 18.609375 23.390625 \r\nQ 18.609375 15.53125 22.484375 10.953125 \r\nQ 26.375 6.390625 33.015625 6.390625 \r\nQ 39.65625 6.390625 43.53125 10.953125 \r\nQ 47.40625 15.53125 47.40625 23.390625 \r\nQ 47.40625 31.296875 43.53125 35.828125 \r\nQ 39.65625 40.375 33.015625 40.375 \r\nz\r\nM 52.59375 71.296875 \r\nL 52.59375 62.3125 \r\nQ 48.875 64.0625 45.09375 64.984375 \r\nQ 41.3125 65.921875 37.59375 65.921875 \r\nQ 27.828125 65.921875 22.671875 59.328125 \r\nQ 17.53125 52.734375 16.796875 39.40625 \r\nQ 19.671875 43.65625 24.015625 45.921875 \r\nQ 28.375 48.1875 33.59375 48.1875 \r\nQ 44.578125 48.1875 50.953125 41.515625 \r\nQ 57.328125 34.859375 57.328125 23.390625 \r\nQ 57.328125 12.15625 50.6875 5.359375 \r\nQ 44.046875 -1.421875 33.015625 -1.421875 \r\nQ 20.359375 -1.421875 13.671875 8.265625 \r\nQ 6.984375 17.96875 6.984375 36.375 \r\nQ 6.984375 53.65625 15.1875 63.9375 \r\nQ 23.390625 74.21875 37.203125 74.21875 \r\nQ 40.921875 74.21875 44.703125 73.484375 \r\nQ 48.484375 72.75 52.59375 71.296875 \r\nz\r\n\" id=\"DejaVuSans-54\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-54\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_5\">\r\n     <g id=\"line2d_7\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"34.240625\" xlink:href=\"#mfd42408965\" y=\"102.06\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_8\">\r\n      <!-- 8 -->\r\n      <g transform=\"translate(20.878125 105.859219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 31.78125 34.625 \r\nQ 24.75 34.625 20.71875 30.859375 \r\nQ 16.703125 27.09375 16.703125 20.515625 \r\nQ 16.703125 13.921875 20.71875 10.15625 \r\nQ 24.75 6.390625 31.78125 6.390625 \r\nQ 38.8125 6.390625 42.859375 10.171875 \r\nQ 46.921875 13.96875 46.921875 20.515625 \r\nQ 46.921875 27.09375 42.890625 30.859375 \r\nQ 38.875 34.625 31.78125 34.625 \r\nz\r\nM 21.921875 38.8125 \r\nQ 15.578125 40.375 12.03125 44.71875 \r\nQ 8.5 49.078125 8.5 55.328125 \r\nQ 8.5 64.0625 14.71875 69.140625 \r\nQ 20.953125 74.21875 31.78125 74.21875 \r\nQ 42.671875 74.21875 48.875 69.140625 \r\nQ 55.078125 64.0625 55.078125 55.328125 \r\nQ 55.078125 49.078125 51.53125 44.71875 \r\nQ 48 40.375 41.703125 38.8125 \r\nQ 48.828125 37.15625 52.796875 32.3125 \r\nQ 56.78125 27.484375 56.78125 20.515625 \r\nQ 56.78125 9.90625 50.3125 4.234375 \r\nQ 43.84375 -1.421875 31.78125 -1.421875 \r\nQ 19.734375 -1.421875 13.25 4.234375 \r\nQ 6.78125 9.90625 6.78125 20.515625 \r\nQ 6.78125 27.484375 10.78125 32.3125 \r\nQ 14.796875 37.15625 21.921875 38.8125 \r\nz\r\nM 18.3125 54.390625 \r\nQ 18.3125 48.734375 21.84375 45.5625 \r\nQ 25.390625 42.390625 31.78125 42.390625 \r\nQ 38.140625 42.390625 41.71875 45.5625 \r\nQ 45.3125 48.734375 45.3125 54.390625 \r\nQ 45.3125 60.0625 41.71875 63.234375 \r\nQ 38.140625 66.40625 31.78125 66.40625 \r\nQ 25.390625 66.40625 21.84375 63.234375 \r\nQ 18.3125 60.0625 18.3125 54.390625 \r\nz\r\n\" id=\"DejaVuSans-56\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-56\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"text_9\">\r\n     <!-- Queries -->\r\n     <g transform=\"translate(14.798437 82.307031)rotate(-90)scale(0.1 -0.1)\">\r\n      <defs>\r\n       <path d=\"M 39.40625 66.21875 \r\nQ 28.65625 66.21875 22.328125 58.203125 \r\nQ 16.015625 50.203125 16.015625 36.375 \r\nQ 16.015625 22.609375 22.328125 14.59375 \r\nQ 28.65625 6.59375 39.40625 6.59375 \r\nQ 50.140625 6.59375 56.421875 14.59375 \r\nQ 62.703125 22.609375 62.703125 36.375 \r\nQ 62.703125 50.203125 56.421875 58.203125 \r\nQ 50.140625 66.21875 39.40625 66.21875 \r\nz\r\nM 53.21875 1.3125 \r\nL 66.21875 -12.890625 \r\nL 54.296875 -12.890625 \r\nL 43.5 -1.21875 \r\nQ 41.890625 -1.3125 41.03125 -1.359375 \r\nQ 40.1875 -1.421875 39.40625 -1.421875 \r\nQ 24.03125 -1.421875 14.8125 8.859375 \r\nQ 5.609375 19.140625 5.609375 36.375 \r\nQ 5.609375 53.65625 14.8125 63.9375 \r\nQ 24.03125 74.21875 39.40625 74.21875 \r\nQ 54.734375 74.21875 63.90625 63.9375 \r\nQ 73.09375 53.65625 73.09375 36.375 \r\nQ 73.09375 23.6875 67.984375 14.640625 \r\nQ 62.890625 5.609375 53.21875 1.3125 \r\nz\r\n\" id=\"DejaVuSans-81\"/>\r\n       <path d=\"M 8.5 21.578125 \r\nL 8.5 54.6875 \r\nL 17.484375 54.6875 \r\nL 17.484375 21.921875 \r\nQ 17.484375 14.15625 20.5 10.265625 \r\nQ 23.53125 6.390625 29.59375 6.390625 \r\nQ 36.859375 6.390625 41.078125 11.03125 \r\nQ 45.3125 15.671875 45.3125 23.6875 \r\nL 45.3125 54.6875 \r\nL 54.296875 54.6875 \r\nL 54.296875 0 \r\nL 45.3125 0 \r\nL 45.3125 8.40625 \r\nQ 42.046875 3.421875 37.71875 1 \r\nQ 33.40625 -1.421875 27.6875 -1.421875 \r\nQ 18.265625 -1.421875 13.375 4.4375 \r\nQ 8.5 10.296875 8.5 21.578125 \r\nz\r\nM 31.109375 56 \r\nz\r\n\" id=\"DejaVuSans-117\"/>\r\n       <path d=\"M 41.109375 46.296875 \r\nQ 39.59375 47.171875 37.8125 47.578125 \r\nQ 36.03125 48 33.890625 48 \r\nQ 26.265625 48 22.1875 43.046875 \r\nQ 18.109375 38.09375 18.109375 28.8125 \r\nL 18.109375 0 \r\nL 9.078125 0 \r\nL 9.078125 54.6875 \r\nL 18.109375 54.6875 \r\nL 18.109375 46.1875 \r\nQ 20.953125 51.171875 25.484375 53.578125 \r\nQ 30.03125 56 36.53125 56 \r\nQ 37.453125 56 38.578125 55.875 \r\nQ 39.703125 55.765625 41.0625 55.515625 \r\nz\r\n\" id=\"DejaVuSans-114\"/>\r\n       <path d=\"M 9.421875 54.6875 \r\nL 18.40625 54.6875 \r\nL 18.40625 0 \r\nL 9.421875 0 \r\nz\r\nM 9.421875 75.984375 \r\nL 18.40625 75.984375 \r\nL 18.40625 64.59375 \r\nL 9.421875 64.59375 \r\nz\r\n\" id=\"DejaVuSans-105\"/>\r\n      </defs>\r\n      <use xlink:href=\"#DejaVuSans-81\"/>\r\n      <use x=\"78.710938\" xlink:href=\"#DejaVuSans-117\"/>\r\n      <use x=\"142.089844\" xlink:href=\"#DejaVuSans-101\"/>\r\n      <use x=\"203.613281\" xlink:href=\"#DejaVuSans-114\"/>\r\n      <use x=\"244.726562\" xlink:href=\"#DejaVuSans-105\"/>\r\n      <use x=\"272.509766\" xlink:href=\"#DejaVuSans-101\"/>\r\n      <use x=\"334.033203\" xlink:href=\"#DejaVuSans-115\"/>\r\n     </g>\r\n    </g>\r\n   </g>\r\n   <g id=\"patch_3\">\r\n    <path d=\"M 34.240625 118.8 \r\nL 34.240625 7.2 \r\n\" style=\"fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;stroke-width:0.8;\"/>\r\n   </g>\r\n   <g id=\"patch_4\">\r\n    <path d=\"M 145.840625 118.8 \r\nL 145.840625 7.2 \r\n\" style=\"fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;stroke-width:0.8;\"/>\r\n   </g>\r\n   <g id=\"patch_5\">\r\n    <path d=\"M 34.240625 118.8 \r\nL 145.840625 118.8 \r\n\" style=\"fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;stroke-width:0.8;\"/>\r\n   </g>\r\n   <g id=\"patch_6\">\r\n    <path d=\"M 34.240625 7.2 \r\nL 145.840625 7.2 \r\n\" style=\"fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;stroke-width:0.8;\"/>\r\n   </g>\r\n  </g>\r\n  <g id=\"axes_2\">\r\n   <g id=\"patch_7\">\r\n    <path clip-path=\"url(#pad60f2df32)\" d=\"M 152.815625 103.77 \r\nL 152.815625 103.451484 \r\nL 152.815625 22.548516 \r\nL 152.815625 22.23 \r\nL 156.892625 22.23 \r\nL 156.892625 22.548516 \r\nL 156.892625 103.451484 \r\nL 156.892625 103.77 \r\nz\r\n\" style=\"fill:#ffffff;stroke:#ffffff;stroke-linejoin:miter;stroke-width:0.01;\"/>\r\n   </g>\r\n   <image height=\"81\" id=\"image3d034b8ab9\" transform=\"scale(1 -1)translate(0 -81)\" width=\"4\" x=\"153\" xlink:href=\"data:image/png;base64,\r\niVBORw0KGgoAAAANSUhEUgAAAAQAAABRCAYAAAD1sgc6AAAAnElEQVR4nJ2SOw7CUBADHxL3PykVFeyXFsaRLJFyNLY3UW77fOz5eu5n+gAMAYzVSJmIL1VQCdBY2Xwbw3eIsc1ISSTcika8QSB3BGf92/oVD1I+IX+HP0rZIcYGQXE25Q4HJscYWmrv6EJp9/6CahoFQyIppQTFSNuVGkaWswRFgNULQyNHDNchdwRPvzBQGmIQvKSUIHip3MHSD/5ryrXugEFNAAAAAElFTkSuQmCC\" y=\"-22\"/>\r\n   <g id=\"matplotlib.axis_3\"/>\r\n   <g id=\"matplotlib.axis_4\">\r\n    <g id=\"ytick_6\">\r\n     <g id=\"line2d_8\">\r\n      <defs>\r\n       <path d=\"M 0 0 \r\nL 3.5 0 \r\n\" id=\"m59c1a2bfa8\" style=\"stroke:#000000;stroke-width:0.8;\"/>\r\n      </defs>\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"156.892625\" xlink:href=\"#m59c1a2bfa8\" y=\"103.77\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_10\">\r\n      <!-- 0.00 -->\r\n      <g transform=\"translate(163.892625 107.569219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 10.6875 12.40625 \r\nL 21 12.40625 \r\nL 21 0 \r\nL 10.6875 0 \r\nz\r\n\" id=\"DejaVuSans-46\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-48\"/>\r\n       <use x=\"63.623047\" xlink:href=\"#DejaVuSans-46\"/>\r\n       <use x=\"95.410156\" xlink:href=\"#DejaVuSans-48\"/>\r\n       <use x=\"159.033203\" xlink:href=\"#DejaVuSans-48\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_7\">\r\n     <g id=\"line2d_9\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"156.892625\" xlink:href=\"#m59c1a2bfa8\" y=\"83.385\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_11\">\r\n      <!-- 0.25 -->\r\n      <g transform=\"translate(163.892625 87.184219)scale(0.1 -0.1)\">\r\n       <use xlink:href=\"#DejaVuSans-48\"/>\r\n       <use x=\"63.623047\" xlink:href=\"#DejaVuSans-46\"/>\r\n       <use x=\"95.410156\" xlink:href=\"#DejaVuSans-50\"/>\r\n       <use x=\"159.033203\" xlink:href=\"#DejaVuSans-53\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_8\">\r\n     <g id=\"line2d_10\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"156.892625\" xlink:href=\"#m59c1a2bfa8\" y=\"63\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_12\">\r\n      <!-- 0.50 -->\r\n      <g transform=\"translate(163.892625 66.799219)scale(0.1 -0.1)\">\r\n       <use xlink:href=\"#DejaVuSans-48\"/>\r\n       <use x=\"63.623047\" xlink:href=\"#DejaVuSans-46\"/>\r\n       <use x=\"95.410156\" xlink:href=\"#DejaVuSans-53\"/>\r\n       <use x=\"159.033203\" xlink:href=\"#DejaVuSans-48\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_9\">\r\n     <g id=\"line2d_11\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"156.892625\" xlink:href=\"#m59c1a2bfa8\" y=\"42.615\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_13\">\r\n      <!-- 0.75 -->\r\n      <g transform=\"translate(163.892625 46.414219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 8.203125 72.90625 \r\nL 55.078125 72.90625 \r\nL 55.078125 68.703125 \r\nL 28.609375 0 \r\nL 18.3125 0 \r\nL 43.21875 64.59375 \r\nL 8.203125 64.59375 \r\nz\r\n\" id=\"DejaVuSans-55\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-48\"/>\r\n       <use x=\"63.623047\" xlink:href=\"#DejaVuSans-46\"/>\r\n       <use x=\"95.410156\" xlink:href=\"#DejaVuSans-55\"/>\r\n       <use x=\"159.033203\" xlink:href=\"#DejaVuSans-53\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n    <g id=\"ytick_10\">\r\n     <g id=\"line2d_12\">\r\n      <g>\r\n       <use style=\"stroke:#000000;stroke-width:0.8;\" x=\"156.892625\" xlink:href=\"#m59c1a2bfa8\" y=\"22.23\"/>\r\n      </g>\r\n     </g>\r\n     <g id=\"text_14\">\r\n      <!-- 1.00 -->\r\n      <g transform=\"translate(163.892625 26.029219)scale(0.1 -0.1)\">\r\n       <defs>\r\n        <path d=\"M 12.40625 8.296875 \r\nL 28.515625 8.296875 \r\nL 28.515625 63.921875 \r\nL 10.984375 60.40625 \r\nL 10.984375 69.390625 \r\nL 28.421875 72.90625 \r\nL 38.28125 72.90625 \r\nL 38.28125 8.296875 \r\nL 54.390625 8.296875 \r\nL 54.390625 0 \r\nL 12.40625 0 \r\nz\r\n\" id=\"DejaVuSans-49\"/>\r\n       </defs>\r\n       <use xlink:href=\"#DejaVuSans-49\"/>\r\n       <use x=\"63.623047\" xlink:href=\"#DejaVuSans-46\"/>\r\n       <use x=\"95.410156\" xlink:href=\"#DejaVuSans-48\"/>\r\n       <use x=\"159.033203\" xlink:href=\"#DejaVuSans-48\"/>\r\n      </g>\r\n     </g>\r\n    </g>\r\n   </g>\r\n   <g id=\"patch_8\">\r\n    <path d=\"M 152.815625 103.77 \r\nL 152.815625 103.451484 \r\nL 152.815625 22.548516 \r\nL 152.815625 22.23 \r\nL 156.892625 22.23 \r\nL 156.892625 22.548516 \r\nL 156.892625 103.451484 \r\nL 156.892625 103.77 \r\nz\r\n\" style=\"fill:none;stroke:#000000;stroke-linejoin:miter;stroke-width:0.8;\"/>\r\n   </g>\r\n  </g>\r\n </g>\r\n <defs>\r\n  <clipPath id=\"p57057f4988\">\r\n   <rect height=\"111.6\" width=\"111.6\" x=\"34.240625\" y=\"7.2\"/>\r\n  </clipPath>\r\n  <clipPath id=\"pad60f2df32\">\r\n   <rect height=\"81.54\" width=\"4.077\" x=\"152.815625\" y=\"22.23\"/>\r\n  </clipPath>\r\n </defs>\r\n</svg>\r\n",
      "text/plain": [
       "<Figure size 180x180 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "attention_weights = torch.eye(10).reshape((1, 1, 10, 10))\n",
    "show_heatmaps(attention_weights, xlabel='Keys', ylabel='Queries')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 人的注意力是有限的、有价值和稀缺的资源\n",
    "* 受试者使用非主动性和自主性提示有选择地引导注意力。前者基于突出性，后者依赖于任务。\n",
    "* 注意力机制与全连接层或者汇聚层的区别源于增加的自主提示\n",
    "* 由于包含了自主性提示，注意力机制与全连接层或汇聚层不同。\n",
    "* 注意力机制通过注意力使选择偏向于值（感官输入），其中包括查询（自主性提示）和键（非自主性提示）。键和值是成对的。\n",
    "* 我们可以可视化查询和键的注意力权重。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch_gpu",
   "language": "python",
   "name": "pytorch_gpu"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
